<?php

class Model {
	// 错误信息
	public $error;
	// 表名称
	public $table;
	// 选项
	public $opt = array(
		'field'=>' * ',
		'where'=>'',
		'group'=>'',
		'having'=>'',
		'order'=>'',
		'limit'=>'',
	);
	// 构造函数
	public function __construct($table=null){
		// 如果子类制定了table的值那就把值赋给table属性
		if($table)$this->table = $table;
		// 链接数据库服务器
		if(!@mysql_connect(C('DB_HOST'),C('DB_USER'),C('DB_PASSWORD'))){
			die('链接数据库服务器失败 |-> '.mysql_error());
		}
		// 设置字符集
		mysql_query('SET NAMES '.C('DB_CHARSET'));
		// 链接数据库
		if(!@mysql_select_db(C('DB_NAME'))){
			die('链接数据库失败 |-> '.mysql_error());
		}
	}
	// 声明字段
	public function field($opt){
		$this->opt['field']=$opt;
		return $this;
	}
	// 声明条件
	public function where($opt){
		$this->opt['where'] = ' WHERE '.$opt;
		return $this;
	}
	// 声明分组
	public function group($opt){
		$this->opt['group'] = ' GROUP BY '.$opt;
		return $this;
	}
	// 声明分组条件
	public function having($opt){
		$this->opt['having'] = ' HAVING '.$opt;
		return $this;
	}
	// 声明排序
	public function order($opt){
		$this->opt['order'] = ' ORDER BY '.$opt;
		return $this;
	}
	// 声明条数
	public function limit($opt){
		$this->opt['limit'] = ' LIMIT '.$opt;
		return $this;
	}
	// 有结果集的查询
	public function query($sql){
		$res = mysql_query($sql);
		if($res){
			$rows = array();
			while ($row = mysql_fetch_assoc($res)) {
				$rows[] = $row;
			}
			return $rows;
		}else{
			die(mysql_error());
		}
	}
	// 没有结果集的查询
	public function exe($sql){
		$res = mysql_query($sql);
		if($res){
			$inId = mysql_insert_id();
			return $inId?$inId:true;
		}else{
			die(mysql_error());
		}
	}
	// 增
	public function insert($data){
		$sql = "INSERT INTO ".$this->table;
		$field = array_keys($data);
		$Val = array_values($data);
		foreach ($Val as $key => $value) {
			$Val[$key] = addslashes($value);
		}
		$sql .= "(".implode(',', $field).") VALUES ('".implode("','", $Val)."')";
		return $this->exe($sql);
	}
	// 删
	public function delete(){
		if(empty($this->opt['where'])) return false;
		$sql = "DELETE FROM ".$this->table.$this->opt['where'].
		$this->opt['order'].$this->opt['limit'];
		return $this->exe($sql);
	}
	// 改
	public function update($data){
		if(empty($this->opt['where'])) return false;
		$sql = "UPDATE ".$this->table." SET ";
		foreach ($data as $key => $value) {
			$sql .= $key ."='$value',";
		}
		$sql = substr($sql, 0,-1).$this->opt['where'];
		return $this->exe($sql);
	}
	// 查询多个语句
	public function select(){
		$sql = "SELECT ".$this->opt['field']." FROM ".$this->table.
		$this->opt['where'].$this->opt['group'].$this->opt['having'].
		$this->opt['order'].$this->opt['limit'];
		return $this->query($sql);
	}
	// 查询一条数据
	public function find(){
		$data = $this->select();
		return $data?current($data):$data;
	}
	// 受影响记录条数
	public function getAffect(){
		return mysql_affected_rows();
	}
	// 数据库记录数
	public function count(){
		$count = $this->query("SELECT count(*) as c FROM ".$this->table." {$this->opt['where']} ");
		return $count[0]['c'];
	}




}


?>